package com.gpframework.config;

import com.gpframework.aspectj.CurrentMemberMethodArgumentResolver;
import com.gpframework.framework.logging.TraceIdHandlerInterceptor;
import com.gpframework.module.interceptor.AuthInterceptor;
import com.gpframework.module.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * web配置
 */
@SuppressWarnings("deprecation")
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private TraceIdHandlerInterceptor traceIdHandlerInterceptor;

    /**
     * 不拦截的资源
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(traceIdHandlerInterceptor).order(Ordered.HIGHEST_PRECEDENCE);
        registry.addInterceptor(authInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/swagger**")
                .excludePathPatterns("/swagger-resources")
                .excludePathPatterns("/doc.html")
                .excludePathPatterns("/v2/**")
                .excludePathPatterns("/file/**")
                //访问附件
                .excludePathPatterns("/profile/**")
                //登录
                .excludePathPatterns("/login/**")
                // TODO:LEE 所有接口关闭认证（测试使用）
                .excludePathPatterns("/**")
        ;
        super.addInterceptors(registry);
    }

    @Bean
    public AuthInterceptor authInterceptor() {
        return new AuthInterceptor(tokenService, null);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).maxAge(3600).allowedMethods("*");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(userResolver());
    }

    @Bean
    public CurrentMemberMethodArgumentResolver userResolver() {
        return new CurrentMemberMethodArgumentResolver();
    }
}
